package com.example.reagent_management.service.works

import android.content.Context
import androidx.hilt.work.HiltWorker
import androidx.work.CoroutineWorker
import androidx.work.Data
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import com.example.reagent_management.ui.message.pojo.Message
import com.example.reagent_management.ui.message.pojo.MessageRepository
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.*

@HiltWorker
class MessageWork @AssistedInject constructor(
    @Assisted context: Context,
    @Assisted workerParameters: WorkerParameters,
    private val mesRepository: MessageRepository,
) : CoroutineWorker(context, workerParameters) {
    override suspend fun doWork(): Result {
        return withContext(Dispatchers.IO) {
            val messages = inputData.getString(MESSAGE_MESSAGES) ?: "|"
            val type = inputData.getInt(MESSAGE_TYPE, 0)
            val remindId = inputData.getLong(MESSAGE_REMIND_ID, 0)
            val remindTime = inputData.getLong(MESSAGE_TIME, Calendar.getInstance().timeInMillis)
            val insertMessage: Long
            val message = Message(messages, type)
            if (remindId == 0L) {
                insertMessage = mesRepository.insertMessage(message)
            } else {
                if (remindTime - System.currentTimeMillis() <= 0L && type == 1) {
                    val string = messages.replaceAfterLast("|","已过期")
                    message.messages = string
                }
                message.remindId = remindId
                insertMessage = mesRepository.insertMessage(message)
            }
            val insertResult: Data = workDataOf(MESSAGE_WORK_RESULT to insertMessage)
            if (insertMessage != -1L) {
                Result.success(insertResult)
            }
            Result.failure(insertResult)
        }
    }

    companion object {
        const val MESSAGE_MESSAGES = "messages"
        const val MESSAGE_TYPE = "type"
        const val MESSAGE_REMIND_ID = "remindId"
        const val MESSAGE_REMIND_DATE = "remindDate"
        const val MESSAGE_TIME = "remindTime"
        const val MESSAGE_WORK_RESULT = "result"
    }
}